﻿using System;
using System.Linq;
using XRM.Security.DataAccess;
using XRM.Security.DataAccess.Helpers;
using XRM.Security.WebUI.Helpers;

namespace XRM.Security.WebUI.Models.Report.ReportBuilder
{
    public class ScsiReportBuilder : ReportBuilderBase
    {
        private readonly IDataManager _dataManager;
        public ScsiReportBuilder(IDataManager dataManager)
        {
            _dataManager = dataManager;
        }

        public override string TemplateFileName
        {
            get { return "Журнал поэкземплярного учета"; }
        }

        public override string Create(CreateReportModel model)
        {
            var endPeriod = model.EndPeriod.Value.AddDays(1);
            var scsiList = _dataManager.UserSkziRepository.GetAll(s => s.SetupDate >= model.StartPeriod && s.SetupDate < endPeriod)
                .Select( s => new
                {
                    s.SkziKind.ShortName,
                    s.CopyNumber,
                    s.UserRegister,
                    s.SetupDate,
                    s.SetupSystemUser,
                    s.DeleteDate,
                    s.DeleteSystemUser,
                    PCSerialNumber = s.PC.SerialNumber,
                    SCSIExemplar = s.SkziKind.RegistrNumber
                } )
                .ToList();
            var report = new SCSILogType
                {
                    CreateDate = DateTime.Now,
                    StartDate = model.StartPeriod.Value,
                    EndDate = model.EndPeriod.Value,
                    SCSI = scsiList.OrderBy(s => s.SetupDate).ThenBy(s => s.UserRegister.LastName).Select((s, i) => new SCSILogTypeSCSI
                        {
                            StringNumber = (i + 1).ToString(),
                            SCSIKind = s.ShortName,
                            RegistrationNumber = s.SCSIExemplar,
                            User = s.UserRegister.FullName(),
                            InstallationDate = s.SetupDate,
                            InstallPerformer = s.SetupSystemUser.FullName(),
                            DeleteDate = s.DeleteDate.GetValueOrDefault(),
                            DeleteDateSpecified = s.DeleteDate.HasValue,
                            DeletePerformer = s.DeleteSystemUser != null ? s.DeleteSystemUser.FullName() : null,
                            SerialNumberSystemUnit = s.PCSerialNumber,
                            SCSIExemplar = s.CopyNumber
                        }).ToArray()
                };
            return CreateXlsxDocument( Utils.SerializeToString( report ) );
        }
    }
}